/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package wave;

import ast.*;
import base.*;
import java.util.Hashtable;
import java.util.Vector;
import trackmsg.EchoMsg;
import trackmsg.TrackCtrlMsg;


/**
 *
 * @author FUJISAI
 */
public class ASTAssignRightIndexExecution extends WaveExecution {
    public ASTAssignRightIndexExecution(WaveHeadParser parser, WaveEnvironment waveEnv) {
        super(parser, waveEnv);
    }

    public void execute(ASTAssignIndexOf asgnIndex, String tail) {
        SimpleNode left = (SimpleNode)asgnIndex.jjtGetChild(0);
        SimpleNode right = (SimpleNode)asgnIndex.jjtGetChild(1);

        SimpleNode l_left = (SimpleNode)left.jjtGetChild(0);
        SimpleNode l_right = (SimpleNode)left.jjtGetChild(1);

        Vector v_right, v_index, v_content, v = new Vector();
        v_right = nodeToVector(l_right);


        if (right instanceof ASTNone) {
            v.add(v_right.size());
        } else {
            v_content = nodeToVector(right);

            for (int i=0;i<v_content.size();i++) {
                for (int j=0;j<v_right.size();j++) {
                    if (v_content.get(i).toString().compareTo(v_right.get(j).toString()) == 0) {
                        v.add(j+1);
                    }
                }
            }
        }

        Hashtable fTab = this.waveEnv.getFrontalTable();

        if (l_left instanceof ASTFrontalVar) {
            fTab.put(l_left.getString(), v);
            //Utilities.WPPrint(fTab);
        }
        else if (l_left instanceof ASTNodalVar) {
            Hashtable nTab = this.kn.getKNNode(
                        this.waveEnv.getCONTENT()).getNodalTable(waveEnv.getColor());

            nTab.put(l_left.getString(), v);
            //Utilities.WPPrint(nTab);
        }

        if (waveEnv.getTrackAddress() != null && tail.equals("")) {
            //Neu tail ma rong thi gui echo la TRUE di
            TrackNode fromTrack = wi.getTrackForest().getTrackNode(waveEnv.getTrackAddress());
            TrackNode.Echo echo = TrackNode.Echo.TRUE;
            //Tao message echo va gui vao TrackQueue
            TrackCtrlMsg msg = new EchoMsg(fromTrack, echo, waveEnv);
            wi.getTrackQueue().incoming(msg);
        } else if(!tail.equals("")){
            Wave newWave = new Wave(tail, new WaveEnvironment(waveEnv));
            waveQueue.incomingFront(newWave);
        }
        waveEnv.dump();
        Utilities.WPPrint("Executed Assign Right Index Done!");
    }

    public Vector nodeToVector(SimpleNode node){
        Vector vector = new Vector();

        if (node instanceof ASTArrayConst) {
            for (int i=0;i<node.jjtGetNumChildren(); i++) {
                SimpleNode child_node = (SimpleNode)node.jjtGetChild(i);

                vector.addAll(getASTNodeValue(child_node));
            }
        }
        else
            vector = getASTNodeValue(node);
        return vector;
    }
}
